<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="sku编码" prop="skuCode">
        <el-input
          v-model="queryParams.skuCode"
          placeholder="请输入商品sku编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="条形码" prop="barcode">
        <el-input
          v-model="queryParams.barcode"
          placeholder="请输入商品条形码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.mall_prod_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="供应商" prop="supplierId">
        <supplier-selection :sourceSupplierId.sync="queryParams.supplierId"></supplier-selection>
      </el-form-item>

      <el-form-item label="品牌" prop="brandName">
        <brand-selection :sourceBrandId.sync="queryParams.brandId" ref="brandRef"></brand-selection>
      </el-form-item>

      <el-form-item label="状态时间" prop="status">
        <el-date-picker
          v-model="statusTimeRange"
          type="datetimerange"
          :picker-options="pickerStatusTimeRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeStatusTime"
          align="right">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="类目" prop="categoryDesc">
        <category-cascader :sourceCategoryId.sync="queryParams.categoryId" @selected="selectedCatogory"></category-cascader>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['prod:prod:add']"
        >添加
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['prod:prod:edit']"
        >修改
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="名称" align="center" prop="name"/>
<!--      <el-table-column label="商品ID" align="center" prop="id"/>-->
      <el-table-column label="图片" align="center" prop="albumThumbnail" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.albumThumbnail" width="50" height="50"></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="类目" align="center" prop="categoryDesc"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="最低参考价" align="center" prop="minReferencePrice"/>
      <el-table-column label="最低销售价" align="center" prop="minSalePrice"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status === 1"
            @change="changeStatus(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          <!--          <dict-tag :options="dict.type.mall_prod_status" :value="scope.row.status"/>-->
        </template>
      </el-table-column>
      <el-table-column label="上下架时间" align="center" prop="statusTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.statusTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="viewSku(scope.row)"
            v-hasPermi="['prod:prod:edit']"
          >查看sku
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['prod:prod:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="sku信息"
      :visible.sync="controlSkuDialogVisible"
      width="900px"
    >
      <el-table :data="skuListData" style="width: 100%">
        <el-table-column label="图片" prop="skuPic" width="100" align="center">
          <template slot-scope="scope">
            <image-preview :src="scope.row.skuPic" width="50" height="50"></image-preview>
          </template>
        </el-table-column>
        <el-table-column label="sku属性" prop="skuAttr" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ mergeAttributeValues(scope.row.skuAttr) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商" prop="supplier" width="100" align="center">
        </el-table-column>
        <el-table-column label="供货价" prop="supplierPrice" width="60" align="center">
        </el-table-column>
        <el-table-column label="参考价" prop="referencePrice" width="60" align="center">
        </el-table-column>
        <el-table-column label="销售价" prop="salePrice" width="60" align="center">
        </el-table-column>
        <el-table-column label="sku编码" prop="skuCode" width="80" align="center">
        </el-table-column>
        <el-table-column label="条形码" prop="barcode" width="80" align="center">
        </el-table-column>
        <el-table-column label="单位" prop="unit" width="50" align="center">
        </el-table-column>
        <el-table-column label="剩余" prop="remained" width="70" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remained }}</span>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="modifyInventory(scope.row)"
              v-hasPermi="['prod:prod:edit']"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="冻结" prop="freezed" width="60" align="center">
        </el-table-column>
        <el-table-column label="已售" prop="saled" width="60" align="center">
        </el-table-column>
      </el-table>

    </el-dialog>

    <el-dialog
      title="修改库存"
      :visible.sync="stockDialogVisible"
      width="30%"
    >
      <span style="margin-right: 15px">库存变量:</span>
      <el-input-number size="medium" v-model="inventoryVariables" @change="numChange" :min="minInventoryVariables"></el-input-number>
      <span slot="footer" class="dialog-footer">
    <el-button @click="stockDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitInventoryVariables">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
import brandSelection from "@/views/components/brandSelection";
import supplierSelection from "@/views/components/supplierSelection";
import CategoryCascader from "@/views/components/categoryCascader";

import {listProd, modifyCommodityStatus} from "@/api/prod/prod";
import {querySkuBasedOnId, updateInventoryVariables} from "@/api/prod/sku";

export default {
  name: "Prod",
  components: {brandSelection, CategoryCascader,supplierSelection},
  dicts: ['mall_prod_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      prodList: [],
      // 弹出层标题
      // title: "",
      // // 是否显示弹出层
      // open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'status_time',
        isAsc: 'descending',
        name: "",
        brandId: null,
        categoryId: null,  //非必传, 搜索框条件查询时可传,必须是三级类目id
        supplierId: null,
        skuCode: "",
        barcode: "",
        status: null,
        statusTimeStart: null,
        statusTimeEnd: null
      },
      controlSkuDialogVisible: false,
      querySkuParameters: {
        pageNum: 1,
        pageSize: 10,
        prodId: null
      },
      skuListData: [],
      stockDialogVisible: false,
      inventoryVariables: 0,
      minInventoryVariables: undefined,

      statusTimeRange: [],
      pickerStatusTimeRange: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      updateInventoryParameters: {
        id: 2,
        inventoryVariation: -100
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.$refs.brandRef.queryBrandList();
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listProd(this.queryParams).then(response => {
        this.prodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.categoryId === 0){
        this.queryParams.categoryId = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.brandId = null;
      this.queryParams.categoryId = null;
      this.queryParams.statusTimeStart = null;
      this.queryParams.statusTimeEnd = null;
      this.statusTimeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    selectedCatogory(level, id){
       if (level == 1){
         this.$modal.msgWarning("请继续选择二级类目!");
       }else if (level == 2){
         this.$modal.msgWarning("请继续选择三级类目!");
       }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const params = {prodId: 0};
      this.$tab.openPage("添加商品", '/prod/publish-brod/index', params);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const prodId = row.id || this.ids;
      const params = {prodId: prodId};
      this.$tab.openPage("修改商品", '/prod/publish-brod/index', params);
    },
    viewSku(row) {
      this.querySkuParameters.prodId = row.id
      querySkuBasedOnId(this.querySkuParameters).then(response => {
        this.skuListData = response.rows
        this.controlSkuDialogVisible = true;
      })
    },
    mergeAttributeValues(attributeValueListStr) {
      // console.log(attributeValueList) [{"颜色": "红色"}, {"运存":"8G"}, {"内存":"128G"}]

      let attributeValueList = JSON.parse(attributeValueListStr);

      let valueArr = [];
      for (let i = 0; i < attributeValueList.length; i++) {
        let item = attributeValueList[i];
        valueArr.push(Object.values(item));
      }
      return valueArr.join(", ");
    },

    changeStatus(row) {
      let prodId = row.id;
      let status = row.status === 1 ? 0 : 1;
      modifyCommodityStatus(prodId, status).then(response => {
        // this.getList();
        row.status = status;
        row.statusTime = new Date();
      })
    },

    modifyInventory(row) {
      this.updateInventoryParameters.id = row.id
      this.minInventoryVariables = -row.remained;
      this.stockDialogVisible = true
    },

    numChange(){
      this.updateInventoryParameters.inventoryVariation = this.inventoryVariables
    },
    submitInventoryVariables(){
      if(this.inventoryVariables !== 0 ){
        updateInventoryVariables(this.updateInventoryParameters).then(response => {
          querySkuBasedOnId(this.querySkuParameters).then(response => {
            this.skuListData = response.rows
            this.stockDialogVisible = false;
            this.inventoryVariables = 0
            this.$modal.msgSuccess("修改成功");
          })
        })
      }
    },
    changeStatusTime() {
      this.queryParams.statusTimeStart = this.statusTimeRange[0];
      this.queryParams.statusTimeEnd = this.statusTimeRange[1];
      this.handleQuery();
    }
  },

  watch: {
    //监听路由中 t 值的变化, 决定是否要刷新table数据(编辑 / 添加商品后,跳回来商品列表时)
    '$route.query.t': {
      handler(timeStamp, oldVal) {
        if (timeStamp){
          // console.log("7777777777777777777777")
          this.handleQuery();
        }
      },
      deep: true
    }
  }
};
</script>
